package cn.kgc.rbac.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.rbac.common.CodeMsg;
import cn.kgc.rbac.common.ResponseResult;
import cn.kgc.rbac.dto.RolePageDTO;
import cn.kgc.rbac.entity.Role;
import cn.kgc.rbac.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2023/1/31
 */
@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("all")
    public ResponseResult getAll() {
        List<Role> list = roleService.list(null);
        return new ResponseResult(CodeMsg.SUCCESS, list, Long.valueOf(list.size()));
    }

    @RequestMapping("saveOrUpdate")
    public  ResponseResult  saveOrUpdate(Role role){
        System.out.println("role = " + role);

        Role roleNameExist = roleService.getOne(new QueryWrapper<Role>().eq("role_name", role.getRoleName()));

        // 判定角色标识是否存在
        if(ObjectUtil.isNotNull(roleNameExist)){
            return new ResponseResult(CodeMsg.ROLE_EXIST);
        }

        //判定角色名是否存在
        Role commentsExist = roleService.getOne(new QueryWrapper<Role>().eq("comments", role.getComments()));

        if(ObjectUtil.isNotNull(commentsExist)){
            return new ResponseResult(CodeMsg.ROLE_EXIST);
        }


        boolean b = roleService.saveOrUpdate(role);

        if(b){
            return  new ResponseResult(CodeMsg.SUCCESS);
        }
        return new ResponseResult(CodeMsg.FAIL);
    }

    @RequestMapping("selectById")
    public ResponseResult selectById(Integer id){
        Role role = roleService.getById(id);
        return new ResponseResult(CodeMsg.SUCCESS,role,null);
    }

    //根据角色id查询角色权限
    @RequestMapping("selectPermissionByRoleId")
    public  ResponseResult  selectPermissionByRoleId(Integer roleId){

        return roleService.selectPermissionByRoleId(roleId);
    }

    // 添加角色权限
    @RequestMapping("addRolePermission")
    public ResponseResult addRolePermission(Integer roleId,String permissionIds){

        return roleService.addRolePermission(roleId,permissionIds);
    }

    //根据id删除角色信息
    @RequestMapping("deleteById")
    public ResponseResult deleteById(String ids){

        return roleService.deleteById(ids);
    }

    @RequestMapping("page")
    public ResponseResult getRolePage(RolePageDTO rolePageDTO) {

        return  roleService.selectByPage(rolePageDTO);
    }
}
